package com.aji.leather1.controller;

import com.aji.allcommon.result.Result;
import com.aji.allcommon.service.FileStorageService;
import com.aji.leather1.config.FileEnvConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/report")
@Api(tags = "获取示范报告模块")
@CrossOrigin
@RequiredArgsConstructor
public class ReportController {

    private final FileEnvConfig fileEnvConfig;
    private final FileStorageService fileStorageService;

    @PostMapping("/wordToUrl")
    public Result wordToUrl(@RequestParam("wordFile") MultipartFile wordFile) throws IOException {
        // 1. 获取原始文件名
        String originalFilename = wordFile.getOriginalFilename();
        if (originalFilename == null || !originalFilename.matches(".*\\.(doc|docx)$")) {
            return Result.error("只支持 Word 文档（.doc / .docx）上传");
        }

        // 2. 可以根据需求改名，比如统一使用 .docx
        String simpFileName = originalFilename;

        // 3. 临时文件保存
        File tempFile = File.createTempFile("tempWord", null);
        wordFile.transferTo(tempFile);

        // 4. 打开文件输入流
        try (FileInputStream fileInputStream = new FileInputStream(tempFile)) {
            // 上传到文件存储服务（假设你的 fileStorageService 提供 uploadFile 方法）
            String accessUrl = fileStorageService.uploadFile("doc/word", simpFileName, fileInputStream, "doc/word");
            return Result.success(accessUrl);
        } finally {
            // 删除临时文件
            tempFile.delete();
        }
    }

//    @ApiOperation("获取 汉唐长安城推广示范")
//    @GetMapping("/ht")
//    public ResponseEntity<byte[]> download(@RequestParam String url) {
//
//    }



    @ApiOperation("获取 石茆推广示范")
    @GetMapping("/sm")
    public void downloadDirect(HttpServletResponse response) throws IOException {
        // 1. 文件路径
        String filePath = "D:/leatherData/石茆推广示范.docx";
        File file = new File(filePath);

        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
            return;
        }

        // 2. 设置下载响应头（处理中文文件名）
        String fileName = URLEncoder.encode(file.getName(), "UTF-8").replaceAll("\\+", "%20");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName);
        response.setContentLengthLong(file.length());

        // 3. 读取文件并写入响应输出流
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             OutputStream os = response.getOutputStream()) {

            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
        }
    }

    @ApiOperation("获取 杨官寨推广示范")
    @GetMapping("/ygz")
    public ResponseEntity<byte[]> getYgzFile() throws IOException {
        String fullPath = fileEnvConfig.getDataPath() + fileEnvConfig.getYgzFile();
        String fileName = fileEnvConfig.getYgzFile();

        File file = new File(fullPath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在：" + fullPath);
        }

        // 使用FileInputStream读取文件
        byte[] bytes = new byte[(int) file.length()];
        FileInputStream fis = new FileInputStream(file);
        fis.read(bytes);
        fis.close();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDisposition(ContentDisposition.attachment().filename(fileName).build());
        headers.setContentLength(bytes.length);

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    /**
     * 根据文件名确定媒体类型
     */
    private MediaType determineMediaType(String fileName) {
        if (fileName == null) {
            return MediaType.APPLICATION_OCTET_STREAM;
        }

        String lowerFileName = fileName.toLowerCase();

        if (lowerFileName.endsWith(".doc")) {
            return new MediaType("application", "msword");
        } else if (lowerFileName.endsWith(".docx")) {
            return new MediaType("application", "vnd.openxmlformats-officedocument.wordprocessingml.document");
        } else if (lowerFileName.endsWith(".pdf")) {
            return MediaType.APPLICATION_PDF;
        } else if (lowerFileName.endsWith(".txt")) {
            return new MediaType("text", "plain", StandardCharsets.UTF_8);
        } else if (lowerFileName.endsWith(".jpg") || lowerFileName.endsWith(".jpeg")) {
            return MediaType.IMAGE_JPEG;
        } else if (lowerFileName.endsWith(".png")) {
            return MediaType.IMAGE_PNG;
        } else {
            // 默认使用二进制流
            return MediaType.APPLICATION_OCTET_STREAM;
        }
    }
}
